import React from 'react';
// 导入action
import { add_message, del_message,get_message_async } from '../redux/actions';

class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state={}
    }
    // 删除留言
    delHandle(id) {
        this.props.store.dispatch(del_message(id));
    }

    // 发布留言
    addHandle() {
        const massage = { content: this.state.content.value.trim(), author: this.state.author.value.trim(), createTime: new Date() }
        if (massage.content === '' || massage.author === '') return alert('请输入完整的表单数据!');
        this.props.store.dispatch(add_message(massage));
        this.state.content.value=this.state.author.value='';
    }


    // 请求默认数据
    componentWillMount(){
        this.props.store.dispatch(get_message_async());
    }
    render() {
        // 获取初始数据
        const store = this.props.store.getState();
        const message=store.message;
        return (
            <div className="container">
                <h1>留言板-Redux版</h1>
                <hr />
                <div className="alert">
                    <form className="form-horizontal">
                        <div className="form-group">
                            <textarea ref={(target) => this.state.content = target} style={{ resize: 'none' }} className="form-control" placeholder="请输入留言内容"></textarea>
                        </div>
                        <div className="form-group">
                            <input ref={(target) => this.state.author = target} type="text" className="form-control" placeholder="请输入留言人" />
                        </div>
                        <div className="form-group">
                            <button onClick={() => this.addHandle()} type="button" className="btn btn-success">提交留言</button>
                        </div>
                    </form>
                </div>
                <hr />
                <ul className="list-group">
                    {
                        message.map(item => (
                            <li key={item.id} className="list-group-item list-group-item-success">
                                <p>{item.content}</p>
                                <p className="clearfix">
                                    <small className="pull-left">留言人:{item.author}</small>
                                    <small className="pull-right">{item.createTime.toLocaleDateString()}</small>
                                </p>
                                <p className="clearfix">
                                    <button className="btn btn-xs btn-danger pull-right" onClick={() => this.delHandle(item.id)}>删除</button>
                                </p>
                            </li>
                        ))
                    }
                </ul>
            </div>
        )
    }
}
export default Message;